package com.kaede.hayate.modules.sys.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.kaede.hayate.common.base.BaseController;
import com.kaede.hayate.common.base.BaseQueryRequest;
import com.kaede.hayate.common.exception.SystemErrorException;
import com.kaede.hayate.config.ApplicationProperties;
import com.kaede.hayate.modules.sys.dto.*;
import com.kaede.hayate.modules.sys.entity.Authority;
import com.kaede.hayate.modules.sys.entity.Role;
import com.kaede.hayate.modules.sys.entity.User;
import com.kaede.hayate.modules.sys.service.IAuthorityService;
import com.kaede.hayate.modules.sys.service.IRoleService;
import com.kaede.hayate.modules.sys.service.IUserService;
import com.kaede.hayate.security.entity.RestUserDetails;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.UUID;

@Api(tags = "系统模块")
@RestController
@RequestMapping("sys")
public class SystemController extends BaseController {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private IUserService userService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IAuthorityService authorityService;

    @Autowired
    private ApplicationProperties applicationProperties;


    @ApiOperation("新增用户")
    @PostMapping("user")
    public ResponseEntity createUser(@RequestBody UserRequest userRequest){
        User user = new User();
        user.setBirthday(userRequest.getBirthday());
        user.setEmail(userRequest.getEmail());
        user.setMobile(userRequest.getMobile());
        user.setSex(userRequest.getSex());
        user.setName(userRequest.getName());
        user.setPassword(passwordEncoder.encode(userRequest.getPassword()));
        user.setUsername(userRequest.getUsername());
        user.setBanFlag(userRequest.getBanFlag());
        user.setTokenSecret(UUID.randomUUID().toString().replace("-", ""));
        Long userId = userService.createUser(user, userRequest.getRoleIds());
        return buildId(userId);
    }


    @ApiOperation("新增角色")
    @PostMapping("role")
    public ResponseEntity createRole(@RequestBody RoleRequest roleRequest){
        Role role = new Role();
        role.setName(roleRequest.getName());
        role.setEnname(roleRequest.getEnname());
        role.setSysFlag(roleRequest.getSysFlag());
        Long roleId = roleService.createRole(role, roleRequest.getAuthorityIds());
        return buildId(roleId);
    }

    @ApiOperation("新增权限")
    @PostMapping("authority")
    public ResponseEntity createAuthority(@RequestBody AuthorityRequest authorityRequest){
        Authority authority = new Authority();
        authority.setUrl(authorityRequest.getUrl());
        authority.setMethod(authorityRequest.getMethod());
        authorityService.insert(authority);
        return buildId(authority.getId());
    }

    @ApiOperation("删除用户")
    @DeleteMapping("user/{id}")
    public ResponseEntity deleteUser(@PathVariable Long id){
        if(id == 1){
            throw new SystemErrorException();
        }
        userService.deleteUserById(id);
        return ResponseEntity.ok().build();
    }

    @ApiOperation("删除角色")
    @DeleteMapping("role/{id}")
    public ResponseEntity deleteRole(@PathVariable Long id){
        if(id == 1){
            throw new SystemErrorException();
        }
        roleService.deleteRoleById(id);
        return ResponseEntity.ok().build();
    }

    @ApiOperation("删除权限")
    @DeleteMapping("authority/{id}")
    public ResponseEntity deleteAuthority(@PathVariable Long id){
        if(id == 1){
            throw new SystemErrorException();
        }
        authorityService.deleteAuthorityById(id);
        return ResponseEntity.ok().build();
    }

    @ApiOperation("更新用户")
    @PutMapping("user/{id}")
    public ResponseEntity updateUser(@PathVariable Long id, @RequestBody UserRequest userRequest){
        User user = new User();
        user.setBirthday(userRequest.getBirthday());
        user.setEmail(userRequest.getEmail());
        user.setMobile(userRequest.getMobile());
        user.setSex(userRequest.getSex());
        user.setName(userRequest.getName());
        //不能修改用户名
//        user.setUsername(userRequest.getUsername());
        user.setBanFlag(userRequest.getBanFlag());
        //如果密码不为空则修改密码
        if(!StringUtils.isEmpty(userRequest.getPassword())){
            user.setPassword(passwordEncoder.encode(userRequest.getPassword()));
        }
        user.setId(id);
        userService.updateUserById(user, userRequest.getRoleIds());
        return ResponseEntity.ok().build();
    }

    @ApiOperation("更新角色")
    @PutMapping("role/{id}")
    public ResponseEntity updateRole(@PathVariable Long id, @RequestBody RoleRequest roleRequest){
        Role role = new Role();
        role.setName(roleRequest.getName());
        role.setEnname(roleRequest.getEnname());
        role.setSysFlag(roleRequest.getSysFlag());
        role.setId(id);
        roleService.updateRoleById(role, roleRequest.getAuthorityIds());
        return ResponseEntity.ok().build();
    }

    @ApiOperation("更新权限")
    @PutMapping("authority/{id}")
    public ResponseEntity updateAuthority(@PathVariable Long id, @RequestBody AuthorityRequest authorityRequest){
        Authority authority = new Authority();
        authority.setUrl(authorityRequest.getUrl());
        authority.setMethod(authorityRequest.getMethod());
        authority.setId(id);
        authorityService.updateById(authority);
        return ResponseEntity.ok().build();
    }

    @ApiOperation("检查用户名是否可用")
    @GetMapping("check/username/{username}")
    public ResponseEntity checkUsername(@PathVariable String username){
        Boolean useable;
        User user = userService.selectOne(new EntityWrapper<User>().eq("username", username));
        if(user != null && user.getId() != null){
            useable = false;
        }else {
            useable = true;
        }
        return buildUseable(useable);
    }

    @ApiOperation("查询用户_id")
    @GetMapping("user/{id}")
    public ResponseEntity getUserById(@PathVariable Long id){
        User user = userService.selectById(id);
        return ResponseEntity.ok(user);
    }

    @ApiOperation("查询用户列表")
    @GetMapping("user")
    public ResponseEntity getUserList(UserQueryRequest userQueryRequest){
        Page<User> page = new Page<>(userQueryRequest.getPageNo(), userQueryRequest.getPageSize(),
                userQueryRequest.getOrderByField(), userQueryRequest.getAsc());
        EntityWrapper<User> entityWrapper = buildBaseEntityWrapper(userQueryRequest);
        if(!StringUtils.isEmpty(userQueryRequest.getUsername())){
            entityWrapper.like("username", userQueryRequest.getUsername());
        }
        if(!StringUtils.isEmpty(userQueryRequest.getName())){
            entityWrapper.like("name", userQueryRequest.getName());
        }
        if(userQueryRequest.getSex() != null){
            entityWrapper.eq("sex", userQueryRequest.getSex());
        }
        if(userQueryRequest.getBirthday() != null){
            entityWrapper.eq("birthday", userQueryRequest.getBirthday());
        }
        if(userQueryRequest.getBanFlag() != null){
            entityWrapper.eq("ban_flag", userQueryRequest.getBanFlag());
        }
        if(!StringUtils.isEmpty(userQueryRequest.getMobile())){
            entityWrapper.like("mobile", userQueryRequest.getMobile());
        }
        if(!StringUtils.isEmpty(userQueryRequest.getEmail())){
            entityWrapper.like("email", userQueryRequest.getEmail());
        }
        return ResponseEntity.ok(userService.selectPage(page, entityWrapper));
    }

    @ApiOperation("查询角色_id")
    @GetMapping("role/{id}")
    public ResponseEntity getRoleById(@PathVariable Long id){
        Role role = roleService.selectById(id);
        return ResponseEntity.ok(role);
    }

    @ApiOperation("查询角色列表")
    @GetMapping("role")
    public ResponseEntity getRoleList(RoleQueryRequest roleQueryRequest){
        Page<Role> page = new Page<>(roleQueryRequest.getPageNo(), roleQueryRequest.getPageSize(),
                roleQueryRequest.getOrderByField(), roleQueryRequest.getAsc());
        EntityWrapper<Role> entityWrapper = buildBaseEntityWrapper(roleQueryRequest);
        if(!StringUtils.isEmpty(roleQueryRequest.getName())){
            entityWrapper.like("name", roleQueryRequest.getName());
        }
        if(!StringUtils.isEmpty(roleQueryRequest.getEnname())){
            entityWrapper.like("enname", roleQueryRequest.getEnname());
        }
        if(roleQueryRequest.getSysFlag() != null){
            entityWrapper.eq("sys_flag", roleQueryRequest.getSysFlag());
        }
        return ResponseEntity.ok(roleService.selectPage(page, entityWrapper));
    }

    @ApiOperation("查询权限_id")
    @GetMapping("authority/{id}")
    public ResponseEntity getAuthorityById(@PathVariable Long id){
        Authority authority = authorityService.selectById(id);
        return ResponseEntity.ok(authority);
    }

    @ApiOperation("查询权限列表")
    @GetMapping("authority")
    public ResponseEntity getAuthorityList(AuthorityQueryRequest authorityQueryRequest){
        Page<Authority> page = new Page<>(authorityQueryRequest.getPageNo(), authorityQueryRequest.getPageSize(),
                authorityQueryRequest.getOrderByField(), authorityQueryRequest.getAsc());
        EntityWrapper<Authority> entityWrapper = buildBaseEntityWrapper(authorityQueryRequest);
        if(!StringUtils.isEmpty(authorityQueryRequest.getUrl())){
            entityWrapper.like("url", authorityQueryRequest.getUrl());
        }
        if(!StringUtils.isEmpty(authorityQueryRequest.getMethod())){
            entityWrapper.like("method", authorityQueryRequest.getMethod());
        }
        return ResponseEntity.ok(authorityService.selectPage(page, entityWrapper));
    }

    @ApiOperation("查询当前用户权限列表")
    @GetMapping("auth")
    public ResponseEntity getCurrentUserAuthorities(){
        RestUserDetails restUserDetails = (RestUserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        HashMap<String, Object> response = new HashMap<>();
        response.put("id", Long.parseLong(restUserDetails.getUserId()));
        response.put("name", restUserDetails.getName());
        response.put("username", restUserDetails.getUsername());
        response.put("roles", restUserDetails.getRoles());
        response.put("authorities", restUserDetails.getAuthorities());
        return ResponseEntity.ok(response);
    }

    public ResponseEntity buildUseable(Boolean useable){
        HashMap<String, Boolean> response = new HashMap<>();
        response.put("useable", useable);
        return ResponseEntity.ok(response);
    }


}
